//
//  KVStatuses.swift
//  KVBestMicroblog
//
//  Created by 李康卫 on 16/7/23.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit

class KVStatuses: NSObject {
   
    /// 微博ID
    var id: Int64 = 0
    
    /// 微博创建时间
    var created_at: String?
    
    /// 微博信息内容
    var text: String?
    
    ///微博的行高
    var homestatusCellHieght: CGFloat?
    
    /// 微博来源
    var source: String?{
        didSet {
            if self.source?.characters.count == 0 {
                source = "未知来源"
            } else {
                let nsSource = source! as NSString
                //rel=\"nofollow\">IT之家</a>截取出IT之家
                let firstRange = nsSource.rangeOfString(">")
                let lastRange = nsSource.rangeOfString("</")
                let range: NSRange = NSRange(location: firstRange.location + 1, length: lastRange.location - firstRange.location - 1)
                let newSubString = nsSource.substringWithRange(range)
                if !newSubString.isEmpty {
                    source = newSubString
                } else {
                    source = "未知来源"
                }
            }
        }
    }
    
    /// 微博配图    // [Int] , [String: AnyObjcet] -> [[String: AnyObjcet]]
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            if pic_urls?.count == 0 {
                return
            }
            //遍历数组中的字典直接转换成URL添加到pictureURL数组
            for picture in pic_urls! {
                let urlString = picture["thumbnail_pic"] as! String
                let URL = NSURL(string: urlString)
                pictureURLs.append(URL!)
            }
        }
    }
    /// 图片的URL
    var pictureURLs = [NSURL]()
    /// 转发数
    var reposts_count: Int = 0
    
    /// 评论数
    var comments_count: Int = 0
    
    /// 表态数
    var attitudes_count: Int = 0
    ///user
    var user: KVUserInfo? 
    ///retweeted_status转发的微博
    var retweeted_status: KVStatuses?
    ///content
    var content: String?
    
    //初始化方法字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        //计算行高
        self.calculateHomeCellHeight()
    }
    override func setValue(value: AnyObject?, forKey key: String) {
        //截取用户
        if "user" == key {
            let userInfo = value as! [String : AnyObject]
            user = KVUserInfo(dic: userInfo)
            return
        }
        //截取转发
        if "retweeted_status" == key {
            let retweetedValue = value as! [String: AnyObject]
            retweeted_status = KVStatuses.init(dict: retweetedValue)
            
            let userName: String = (self.user?.screen_name)!
            let text: String = self.text!
            
            let content = "@ \(userName): \(text)"
            self.retweeted_status!.content = content
            return
        }
        super.setValue(value, forKey: key)  
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
//    计算行高
    private func calculateHomeCellHeight() {
        var height: CGFloat = homeCellSpace + homeCellSpace + homeIconViewHeight + homeCellSpace
 

        // cell顶部间距高度(8) + 头像顶部间距(8) + 头像高度(35) + 文字顶部高度(8) + 文字高度(?) + 文字底部(8)
        // 原创配图: + 配图高度(?) + 配图底部(8)
        // 被转发微博: + 被转发文字顶部(8) + 被转发文字(?) + 被转发文字底部(8)
        // 被转发微博配图: + 被转发配图高度(?) + 被转发配图底部间距(8)
        // 底部按钮高度
        if let Text = self.text {
            let nsText = Text as NSString
//           let textHeight = nsText.boundingRectWithSize(CGSize(width: UIScreen.width() - 2*homeCellSpace, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesFontLeading, attributes: [NSAttachmentAttributeName: UIFont.systemFontOfSize(homeTextSize)], context: nil).height
             let textHeight = nsText.boundingRectWithSize(CGSize(width: UIScreen.width() - 2 * homeCellSpace, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(homeTextSize)], context: nil).height
            height += textHeight
        }
        height += homeCellSpace

        // 原创配图: + 配图高度(?) + 配图底部(8)
        let originPictureCount = self.pic_urls?.count
        if originPictureCount > 0 {
            let oringinSize = setupFrame(originPictureCount!)
            height += oringinSize.height
            height += homeCellSpace

        }
        // 判断是否有被转发微博
        if let rewteetedStatus = self.retweeted_status {
            height += homeCellSpace
            let rewContent = (rewteetedStatus.content)! as NSString
             height += rewContent.boundingRectWithSize(CGSize(width: UIScreen.width() - 2*homeCellSpace, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(homeTextSize)], context: nil).height
            height += homeCellSpace
            // 被转发微博配图: + 被转发配图高度(?) + 被转发配图底部间距(8)
               let rewPictureCount = rewteetedStatus.pictureURLs.count
            if rewPictureCount > 0 {
                let rewsize = setupFrame(rewPictureCount)

                height += rewsize.height
                height += homeCellSpace
            }
        }
        
        height += homeFooterHeight
        
       self.homestatusCellHieght = height
    }
    func setupFrame(pictureCount: Int) -> CGSize {
        
        var numberColumn = 3
        if  pictureCount == 1 {
            numberColumn = 1
        } else if pictureCount == 2 || pictureCount == 4 {
            numberColumn = 2
        }
        
        let pictureMargin = homeCellSpace/2
        
        //设置宽高
        let pictureWH: CGFloat = (UIScreen.width() - homeCellSpace*2  - 2*pictureMargin)/3
        
      
        let totalW: CGFloat = CGFloat(numberColumn)*pictureWH + CGFloat(numberColumn - 1)*pictureMargin
        //返回高度
        if pictureCount == 0 {
            return CGSizeZero
        }
        
        // 总行数 = (总数 + 总列数 - 1) / 总列数, 前提保证都是整数
        let numberOfRow = (pictureCount + numberColumn - 1) / numberColumn
        
        // 计算高度 = 总行数 * 图片高度 + (总行数 - 1) * 图片的间距
        let totalH = CGFloat(numberOfRow) * pictureWH + (CGFloat(numberOfRow) - 1) * pictureMargin
        
        let size = CGSizeMake(totalW, totalH)
        
        return size
    }
}
